define(["jquery", "easy-admin"], function ($, ea) {

    var form = layui.form;
    var table = layui.table;
    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'system.database/index'
    };

    var Controller = {

        index: function () {

            var userTable=ea.table.render({
                init: init,
                limit: 100,
                page: false,
                toolbar: [],
                defaultToolbar: false,
                cols: [[
                    {type: 'checkbox'},
                    {field: 'Baoliu', title: '保留表', width: 75},
                    {field: 'Name', title: '数据表', align: 'left'},
                    {field: 'Comment', title: '表名'},
                    {field: 'Engine', title: '表引擎'},
                    {field: 'Rows', title: '记录条数', align: 'center'},
                    {field: 'size', title: '占用空间', align: 'center'},
                    {field: 'Collation', title: '编码', align: 'center'},
                    {field: 'Create_time', title: '创建时间', align: 'center'},
                    {field: 'Name', title: '备份状态', align: 'center',
                        templet: function (d) {
                            return "<div id='db" + d.Name + "'>未备份</div>";
                        }
                    }
                ]]
            });


            $(document).on("click", ".layui-btn", function () {
                var type = $(this).data('type');
                active[type] && active[type].call(this);
            });

            var next=0;

            function initDb() {
                ea.request.post({
                    url: '/admin/system.database/init',
                }, function (res) {
                    next=0;
                    layer.alert(res.msg, { icon: 1, closeBtn: 0 }, function (index) {
                        userTable.reload();
                        layer.close(index);
                    });
             });
            }
            //触发事件
            var active = {
                //初始化
                init: function () {
                    ea.msg.confirm('初始化之后除系统保留表外，其余所有数据表均会清空！点击确认后：将先备份所有表再执行初始化操作', function () {
                        next=1;
                        $('body').find("[lay-filter='layTableAllChoose']").next('div').click();
                        active['export'].call(this);
                    });
                },
                //优化
                optimize: function () {
                    var checkRows = table.checkStatus(init.table_render_id);
                    if (checkRows.data.length === 0) {
                        layer.msg('请选择要优化的数据表', {icon: 2, time: 1000});
                        return;
                    }
                    var ids = checkRows.data.map(function (d) {
                        return d.Name;
                    });
                    layer.msg('正在处理请勿刷新页面', {icon: 16, shade: 0.01, time: 1000000});
                    $.ajax({
                        type: "POST",
                        url: "/admin/system.database/optimize?tablename=" + ids,
                        dataType: 'json',
                        success: function (res) {
                            layer.closeAll();
                            if (res.code) {
                                ea.msg.success(res.msg);
                            } else {
                                ea.msg.error(res.msg, {icon: 2, time: 1000});
                            }
                        },
                        error: function () {
                            layer.closeAll();
                            layer.msg(res.msg, {icon: 2, time: 1000});
                        }
                    });
                    return false;
                },
                //修复
                repair: function () {
                    var checkRows = table.checkStatus(init.table_render_id);
                    if (checkRows.data.length === 0) {
                        layer.msg('请选择要修复的数据表', {icon: 2, time: 1000});
                        return;
                    }
                    var ids = checkRows.data.map(function (d) {
                        return d.Name;
                    });
                    layer.msg('正在处理请勿刷新页面', {icon: 16, shade: 0.01, time: 1000000});
                    $.ajax({
                        type: "POST",
                        url: "/admin/system.database/repair?tablename=" + ids,
                        dataType: 'json',
                        success: function (res) {
                            layer.closeAll();
                            if (res.code) {
                                ea.msg.success(res.msg);
                            } else {
                                ea.msg.error(res.msg, {icon: 2, time: 1000});
                            }
                        },
                        error: function () {
                            layer.closeAll();
                            layer.msg(res.msg, {icon: 2, time: 1000});
                        }
                    });
                    return false;
                },
                //备份
                export: function () {
                    var tables = [];

                    var title='将备份所有数据表';
                    var checkRows = table.checkStatus(init.table_render_id);
                    if (checkRows.data.length === 0) {
                        tables = 'all';
                        // layer.msg('请选择数据表', {icon: 2, time: 1000});
                        // return;
                    } else {
                        title='将备份表：';
                        var name='';
                        tables = checkRows.data.map(function (d) {
                            name+='<br>'+d.Name;
                            return d.Name;
                        });
                        title=title+name;
                    }
                    ea.msg.confirm(title, function () {

                        $item = $(this);
                        var disabled = $item.attr('data-disabled');
                        if (1 == disabled) {
                            return false;
                        }
                        $item.addClass("layui-disabled").attr('data-disabled', 1);
                        $item.find('span').html("正在发送备份请求...");
                        $.post("/admin/system.database/export", {tables: tables},
                            function (res) {
                                if (res.code) {
                                    tables = res.tables;
                                    var loading = ea.msg.success('正在备份表(<font id="upgrade_backup_table">' + res.tab.table + '</font>)……<font id="upgrade_backup_speed">0.01</font>%');
                                    $item.find('span').html(res.msg);
                                    backup(res.tab);
                                    window.onbeforeunload = function () {
                                        return "正在备份数据库，请不要关闭！"
                                    }
                                } else {
                                    layer.msg(res.msg, {icon: 2, time: 1500});
                                    $item.removeClass("layui-disabled").attr('data-disabled', 0);
                                    $item.find('span').html("立即备份");
                                }
                            }, "json");
                        return false;

                        function backup(tab, status) {
                            status && showmsg(tab.id, "开始备份……(0%)");
                            $.post("/admin/system.database/export", tab, function (data) {
                                if (data.code) {
                                    if (tab.table) {
                                        showmsg(tab.id, data.msg);
                                        $('#upgrade_backup_table').html(tab.table);
                                        $('#upgrade_backup_speed').html(tab.speed);
                                        $item.find('span').html('正在备份……' + tab.speed + '%');
                                    } else {
                                        $item.find('span').html('进入备份……');
                                    }
                                    if (!$.isPlainObject(data.tab)) {
                                        // var loading = layer.msg('备份完成……100%，请不要关闭本页面！', {
                                        //     icon: 1,
                                        //     time: 2000,  //1小时后后自动关闭
                                        //     shade: [0.2] //0.1透明度的白色背景
                                        // });
                                        $item.removeClass("layui-disabled").attr('data-disabled', 0);
                                        $item.find('span').html("开始备份");
                                        setTimeout(function () {
                                            layer.closeAll();
                                            layer.msg('备份成功！', {icon: 1, title: false},function () {
                                                if(next==1){
                                                    initDb();
                                                }
                                            });
                                        }, 1000);
                                        window.onbeforeunload = function () {
                                            return null
                                        }
                                        return;
                                    }
                                    backup(data.tab, tab.id != data.tab.id);
                                } else {
                                    layer.closeAll();
                                    $item.removeClass("layui-disabled").attr('data-disabled', 0);
                                    $item.find('span').html("立即备份");
                                }
                            }, "json");
                        }

                        function showmsg(id, msg) {
                            $("#db" + tables[id]).html(msg);
                        }

                    });
                }
            };


            ea.listen();
        },
        restore: function () {

            var userTable = ea.table.render({
                init: {
                    table_elem: '#currentTable',
                    table_render_id: 'currentTableRenderId',
                    index_url: 'system.database/restore',
                    delete_url: 'system.database/delete',
                },
                limit: 100,
                page: false,
                toolbar: ['refresh',
                    'delete'],
                defaultToolbar: false,
                cols: [[
                    {type:'checkbox'},
                    {field: 'basename', title: '文件名称',},
                    {field: 'version', title: '系统版本'},
                    {field: 'part', title: '卷号'},
                    {field: 'size', title: '数据大小',align: 'center'},
                    {field: 'showtime', title: '备份时间',align: 'center'},
                    {align: 'center', toolbar: '#operat', title: '操作', minWidth: 250}
                ]]
            });


            $(document).on("click", ".layui-btn,.case", function () {
                var type = $(this).data('type');
                active[type] && active[type].call(this);
            });

            /*触发事件*/
            var active = {
                // 恢复
                new_import: function(){
                    var obj = this;
                    var importtime = $(obj).attr('data-id');
                    layer.msg('确认还原数据吗？', {
                        btnAlign: 'c',
                        time: 0,
                        btn: ['确定', '取消'],
                        yes: function(index, layero){
                            layer.close(index);
                            layer.msg('还原中请勿刷新页面', {icon: 16,shade: 0.01});
                            $.ajax({
                                type: "POST",
                                url: ea.url('system.database/new_import')+"?time="+importtime,
                                dataType: 'json',
                                success: function (res) {
                                    layer.closeAll();
                                    if(res.code == 1){
                                        layer.msg(res.msg, {icon: 1, time:1000});
                                    }else{
                                        layer.msg(res.msg, {icon: 2,time:1000});
                                    }
                                },
                                error:function(){
                                    layer.closeAll();
                                    layer.msg("未知错误，操作中断！", {icon: 2,time:1000});
                                }
                            });
                        }
                    });
                },
                // 下载
                xaizai: function(){
                    var obj = this;
                    var url = $(obj).attr('data-url');
                    var xaizaitime = $(obj).attr('data-id');
                    window.location.href = ea.url('system.database/downFile')+"?time="+xaizaitime;
                }
            }
            ea.listen();
        },sql:function () {
            $(document).on("click", "#execute", function () {
                $.ajax({
                    type: "POST",
                    url: ea.url('system.database/sql'),
                    data:{
                        prefix:$('#prefix').val(),
                        sql:$('#sql').val()
                    },
                    dataType: 'json',
                    success: function (res) {

                                if (res.code == 1) {
                                    layer.msg(res.msg, {icon: 1, time: 1000},function () {
                                        location.reload();
                                    });
                                } else {
                                    layer.alert(res.msg);
                                }

                }
                })
            });
        }
    };
    return Controller;
});